package com.zsxb.crm.task;

import com.zsxb.crm.mapper.ClueMapper;
import com.zsxb.crm.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

@Slf4j
@Component
public class UpdateReportData {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClueMapper clueMapper;

    @Scheduled(cron = "0 0 1 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void updateReportData(){
        log.info("开始更新report_statistics表内容");

        LocalDate yesterday = LocalDate.now().minusDays(1);
        // 昨天开始时间
        LocalDateTime startOfDay = yesterday.atStartOfDay();
        // 昨天结束时间
        LocalDateTime endOfDay = yesterday.atTime(LocalTime.MAX);
        // 每日新线索数
        Integer newClue = clueMapper.queryNewClueByDate(startOfDay, endOfDay);
        // 总线索数
        Integer totalClue = clueMapper.quertAll();
        // 每日新用户数
        Integer newUser = userMapper.queryNewUserByDate(startOfDay, endOfDay);
        // 总用户数
        Integer totalUser = userMapper.queryAll();

        clueMapper.addClueDataByDate(yesterday, newClue, totalClue);
        userMapper.addUserDataByDate(yesterday, newUser, totalUser);

        log.info("更新report_statistics表内容---date:{}, newUser:{}, totalUser:{}, newClue:{}, totalClue{}",yesterday,newUser,totalUser,newClue,totalClue);

    }

}
